<?php
namespace DRY\Warehouse;

/**
 * DonReY Framework 2012 :: Analyzer for image files
 *
 * @author Wavetrex <wavetrex@gmail.com>
 * @link http://www.donrey.net/Documentation/Modules/warehouse.html#analyzer-image
 * @license [GPL v3] http://www.gnu.org/licenses/gpl-3.0.html
 * @version 1.0.dev
 * @package DonReY
 * @subpackage Module.Render
 */
class Analyzer_Image implements Analyzer
{
	public static function register_Mime_Types()
	{
		// these are the mime types for which this analyzer module responds
		return array(
			image_type_to_mime_type(IMAGETYPE_GIF),
			image_type_to_mime_type(IMAGETYPE_JPEG),
			image_type_to_mime_type(IMAGETYPE_PNG),
			image_type_to_mime_type(IMAGETYPE_SWF),
			image_type_to_mime_type(IMAGETYPE_PSD),
			image_type_to_mime_type(IMAGETYPE_BMP),
			image_type_to_mime_type(IMAGETYPE_TIFF_II),
			image_type_to_mime_type(IMAGETYPE_TIFF_MM),
			image_type_to_mime_type(IMAGETYPE_JP2),
			image_type_to_mime_type(IMAGETYPE_SWC),
			image_type_to_mime_type(IMAGETYPE_IFF),
			image_type_to_mime_type(IMAGETYPE_WBMP),
			image_type_to_mime_type(IMAGETYPE_XBM),
			image_type_to_mime_type(IMAGETYPE_ICO),
			'image/vnd.adobe.photoshop'
		);
	}

	/**
	 * @see \DRY\Warehouse\Analyzer::study()
	 * @param array $fileinfo
	 * @param SimpleXMLElement $CFG
	 */
	public function __construct(&$fileinfo, $CFG)
	{
		$imageinfo = array();
		$imagedata = getimagesize($fileinfo['fullpath'], $imageinfo);

		if($imagedata!==false) {
			$fileinfo['_image'] = array(
				'width'=> $imagedata[0],
				'height'=> $imagedata[1],
				'type'=> $imagedata['mime'],
			);
			if(isset($imagedata['bits']))
				$fileinfo['_image']['bits'] = $imagedata['bits'];
			if(!empty($imageinfo))
				$imagedata['_image']['info'] = $imageinfo;

			// try to read Exif for image/jpeg
			if($CFG['exif']=='true' && $fileinfo['mimetype'] == 'image/jpeg') {
				$exif = $this-> get_Image_Exif($fileinfo['fullpath'], $CFG['exifThm']=='true');
				if($exif!==false)
					$fileinfo['_image']['exif'] = $exif;
			}
		}
	}

    /**
     * Reads EXIF data from an image
     *
     * @param string $filepath
     * @param bool $get_thumbnail
     * @param bool $remove_makernote
     */
	public function get_Image_Exif($filepath, $get_thumbnail = false, $remove_makernote = true)
	{
		$exif = exif_read_data($filepath, null, true, $get_thumbnail);

		if($exif === false)
			return false; // no exif header found (or not really a jpeg)

		if($remove_makernote) { // remove this, can't decode it yet.
			unset($exif['EXIF']['MakerNote']);
		}
		// remove [FILE], it's irrelevant ( data not actually stored inside image )
		unset($exif['FILE']);

		return $exif;
	}

}
